﻿using PasswordManagerMVC.Models;
using PasswordManagerMVC.Utilities;
using PwdMgr.PwdMgrService.UserAuthentication;
using PwdMgr.Utility;
using PwdMgr.Utility.Exceptions;
using System;
using System.Web.Mvc;

namespace PasswordManagerMVC.Controllers
{
    public class AccountController : Controller
    {
        public AccountController()
        {
            _authService = IOCContainer.Resolve<IAuth>("DefaultAuthService");
        }

        private IAuth _authService;

        //
        // GET: /Account/

        public ActionResult Index()
        {
            return RedirectToAction("LogOn");
        }

        public ActionResult LogOn()
        {
            if (SessionManager.HasUser(HttpContext))
            {
                return RedirectToAction("Index", "Search");
            }
            else
            {
                return View();
            }
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel userInfo)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    int uid = _authService.Login(userInfo.UserName, userInfo.Password);

                    SessionManager.AddUser(HttpContext, uid, userInfo.UserName);
                    return RedirectToAction("Index", "Search");
                }
                catch (InvalidUsernamePasswordException)
                {
                    ModelState.AddModelError("",
                        "The user name or password is not correct.");
                }
                catch (Exception ex)
                {
#if DEBUG
                    ModelState.AddModelError("",
                        ex.ToString());
#else
                    ModelState.AddModelError("",
                        ex.Message);
#endif
                }
            }

            return View(userInfo);
        }

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    _authService.CreateUser(PasswordManagerMVC.Utilities.Converter.ToUserInfo(model));
                    return RedirectToAction("LogOn");
                }
                catch (UserAlreadyExistException)
                {
                    ModelState.AddModelError("",
                        "The user already exist.");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("",
                        ex.ToString());
                }
            }

            model.Password = null;
            model.ConfirmPassword = null;
            return View(model);
        }

    }
}
